package com.autonavi.collapse.task;

import com.autonavi.collapse.task.context.TaskComponentContainer;

import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

public class TaskExecutorManager {

    private Map<String, TaskFactory> executorFactoryMap = new HashMap<>();

    public TaskExecutorManager() {
        ServiceLoader<TaskFactory> serviceLoader = ServiceLoader.load(TaskFactory.class);
        for (TaskFactory taskFactory : serviceLoader) {
            executorFactoryMap.put(taskFactory.getType(), taskFactory);
        }
    }

    public void init() throws Exception {
        Map<String, TaskFactory> components = TaskComponentContainer.getComponents(TaskFactory.class);
        for (TaskFactory taskFactory : components.values()) {
            executorFactoryMap.put(taskFactory.getType(), taskFactory);
        }
        for (TaskFactory taskFactory : executorFactoryMap.values()) {
            taskFactory.init();
        }
    }

    public void addFactory(TaskFactory taskFactory) {
        if (taskFactory != null) {
            executorFactoryMap.putIfAbsent(taskFactory.getType(), taskFactory);
        }
    }

    public TaskFactory find(String type) {
        return executorFactoryMap.get(type);
    }
}
